/**
 *
 * @Creater zhangruifeng
 * Aug 20, 2008
 * @Version 1.0
 **/
package com.pub.functions;

import android.annotation.SuppressLint;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

public class DateFuncs {
	public static final String[] WEEKDAY_NAMES = new String[] { "星期日", "星期一",
			"星期二", "星期三", "星期四", "星期五", "星期六" };
	@SuppressLint("SimpleDateFormat")
	private static SimpleDateFormat dateTimeFormat = new SimpleDateFormat(
			"yyyy.MM.dd HH:mm:ss");

	/*
	 * @update zhuangzhonglong
	 * 
	 * @describe 添加更方便的调用接口
	 * 
	 * @time 2008-9-16 19:30:27
	 */
	public static String toString(Date date) {
		return dateTimeToStr(date, "yyyy-MM-dd HH:mm:ss");
	}

	public static String toDateString(Date date) {
		return dateTimeToStr(date, "yyyy-MM-dd");
	}

	/**
	 * 日期时间转字符串
	 * 
	 * @param date
	 *            DATE型
	 * @param dateTimeFormatStr
	 *            格式
	 * @return
	 * 
	 *         示例：当前日期：2007年07月01日12时14分25秒。 dateTimeToStr(new
	 *         Date(),"yyyy-MM-dd HH:mm:ss"); 返回：2007-07-01 12:14:25
	 */
	@SuppressLint("SimpleDateFormat")
	public static String dateTimeToStr(Date date, String dateTimeFormatStr) {
		if (null == date)
			return "";
		String rsStr = null;
		if (dateTimeFormatStr != null) {
			SimpleDateFormat df = new SimpleDateFormat(dateTimeFormatStr);
			rsStr = df.format(date);
		} else {
			rsStr = dateTimeFormat.format(date);
		}
		return rsStr;
	}

	/**
	 * 字符串转日期时间
	 * 
	 * @param dateStr
	 *            字符串
	 * @param dateTimeFormatStr
	 *            格式
	 * @return
	 * 
	 *         示例：当前日期：2007年07月01日12时14分25秒。 dateTimeToStr("2007-07-01
	 *         12:14:25","yyyy-MM-dd HH:mm:ss"); 返回：Date
	 */
	@SuppressLint("SimpleDateFormat")
	public static Date strToDateTime(String dateStr, String dateTimeFormatStr) {
		Date rsDate = null;
		if (StrFuncs.isEmpty(dateStr)) {
			return null;
		}
		if (dateTimeFormatStr != null) {
			SimpleDateFormat df = new SimpleDateFormat(dateTimeFormatStr);
			try {
				rsDate = df.parse(dateStr);
			} catch (Exception e) {
				rsDate = new Date();
				e.printStackTrace();
			}
		} else {
			try {
				rsDate = dateTimeFormat.parse(dateStr);
			} catch (Exception e) {
				rsDate = new Date();
				e.printStackTrace();
			}
		}
		return rsDate;
	}

	/**
	 * add ljk
	 * 
	 * @param dateStr
	 * @return
	 */
	@SuppressLint("SimpleDateFormat")
	public static Date strToDate(String dateStr) {
		Date rsDate = null;
		if (dateStr.length() == 10) {
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			try {
				rsDate = df.parse(dateStr);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (dateStr.length() == 13) {
			try {
				rsDate = strToDateTime(dateStr, "yyyy-MM-dd HH");
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (dateStr.length() > 13) {
			try {
				rsDate = strToDateTime(dateStr, "yyyy-MM-dd HH:mm:ss");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return rsDate;
	}

	@SuppressLint("SimpleDateFormat")
	public static Date strToDateIb(String dateStr) throws Exception {
		Date rsDate = null;

		if (dateStr.length() == 10) {
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			rsDate = df.parse(dateStr);
			return rsDate;
		} else if (dateStr.length() > 10) {
			rsDate = strToDateTime(dateStr, "yyyy-MM-dd HH:mm:ss");
			return rsDate;
		}
		return rsDate;
	}

	public static Date addDay(Date date, int dayCount) {
		GregorianCalendar gc = new GregorianCalendar();
		gc.setTime(date);
		gc.add(5, dayCount);
		return gc.getTime();
	}

	public static Date addMinute(Date date, int minuteCount) {
		GregorianCalendar cal = new GregorianCalendar();
		cal.setTime(date);
		cal.add(Calendar.MINUTE, minuteCount);
		return cal.getTime();
	}

	public static Date addHour(Date date, int hourCount) {
		GregorianCalendar cal = new GregorianCalendar();
		cal.setTime(date);
		cal.add(Calendar.HOUR_OF_DAY, hourCount);
		return cal.getTime();
	}

	/**
	 * 获取传入日期之后的count天（包括传入日期）的日期字符串和星期字符串
	 * 
	 * @param startDate
	 *            字符串
	 * @return
	 * 
	 *         示例：当前日期：2008-8-24。 getDateAndDayByCount("2008-8-24);
	 *         返回：2008-8-24（星期日）........
	 */
	@SuppressWarnings("deprecation")
	public static List<String> getDateAndDayByCount(String startDate,
                                                    Integer count) {
		List<String> weekList = new ArrayList<String>();
		Date current = strToDateTime(startDate, "yyyy-MM-dd");
		int day = current.getDay();
		String week = WEEKDAY_NAMES[day];
		weekList.add(dateTimeToStr(current, "yyyy-MM-dd") + "(" + week + ")");
		current = addDay(current, 1);
		for (int i = 1; i < count; i++) {
			int _day = current.getDay();
			String _week = WEEKDAY_NAMES[_day];
			weekList.add(dateTimeToStr(current, "yyyy-MM-dd") + "(" + _week
					+ ")");
			current = addDay(current, 1);
		}
		return weekList;
	}

	/**
	 * by linjiekai 增加几个小时
	 * 
	 * @param date
	 * @param hour
	 * @return
	 */
	public static Date addHour(int hour) {
		Calendar calendar = Calendar.getInstance();
		Date myDate = new Date();
		calendar.setTime(myDate);
		calendar.add(Calendar.HOUR_OF_DAY, hour);
		return calendar.getTime();
	}

	/**
	 * by panshaohua 增加几个月
	 * 
	 * @param date
	 * @param hour
	 * @return
	 */
	public static Date addMonth(Date nowDate, int month) {
		Calendar calendar = Calendar.getInstance();
		if (null == nowDate) {
			Date myDate = new Date();
			calendar.setTime(myDate);
		} else
			calendar.setTime(nowDate);

		calendar.add(Calendar.MONTH, month);
		return calendar.getTime();
	}

	/**
	 * by linjiekai 增加几分钟
	 * 
	 * @param date
	 * @param minute
	 *            分钟
	 * @return
	 */
	public static Date addMinute(int minute) {
		Calendar calendar = Calendar.getInstance();
		Date myDate = new Date();
		calendar.setTime(myDate);
		calendar.add(Calendar.MINUTE, minute);
		return calendar.getTime();
	}

	@SuppressWarnings("deprecation")
	public static void main(String adf[]) {
		String dat = "2008-09-10 18:17";
		System.out.println(new Date().toLocaleString());
		System.out.println(strToDateTime(dat, "yyyy-MM-dd HH:mm"));
	}

	/*
	 * @update zhuangzhonglong
	 * 
	 * @describe 获取星期几（０为星期天，１为星期一）
	 * 
	 * @time 2008-9-22 2:21:23
	 */
	public static Integer getWeekNo(Date date) {
		GregorianCalendar cal = new GregorianCalendar();
		cal.setTime(date);
		return cal.get(Calendar.DAY_OF_WEEK) - 1;
	}

	/*
	 * @update zhuangzhonglong
	 * 
	 * @describe 从分钟转为时间(hh:mm)
	 * 
	 * @time 2008-9-22 12:26
	 */
	@SuppressLint("DefaultLocale")
	public static String minuteToTime(Integer minute) {
		if (minute == null) {
			return "";
		}
		return String.format("%02d:%02d", (minute - minute % 60) / 60,
				minute % 60);
	}

	/*
	 * @update zhuangzhonglong
	 * 
	 * @describe 获取当前分钟数(0点算起)
	 * 
	 * @time 2008-9-23
	 */
	public static Integer getMinute(Date date) {
		GregorianCalendar cal = new GregorianCalendar();
		cal.setTime(date);
		return cal.get(Calendar.HOUR_OF_DAY) * 60 + cal.get(Calendar.MINUTE);
	}

	/*
	 * @update zhuangzhonglong
	 * 
	 * @describe 截掉Date的时间部分
	 * 
	 * @time 2008-9-24 9:52
	 */
	public static Date trunc(Date date) {
		if (date == null) {
			return null;
		}
		GregorianCalendar cal = new GregorianCalendar();
		cal.setTime(date);
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MILLISECOND, 0);
		return cal.getTime();
	}

	public static Integer dayDiff(Date startDate, Date endDate) {
		long msDiff = trunc(endDate).getTime() - trunc(startDate).getTime();
		return (int) (msDiff / (1000 * 60 * 60 * 24));
	}

	public static Timestamp timeAdd(Timestamp srcTime, int unit, int value) {
		if (srcTime == null)
			return null;
		Calendar c = Calendar.getInstance();
		c.setTime(srcTime);
		c.set(unit, c.get(unit) + value);
		return new Timestamp(c.getTimeInMillis());
	}

	public static Date strToTime(String dateStr) {
		Date rsDate = null;
		if (dateStr.length() == 8) {
			try {
				String date = dateTimeToStr(new Date(), "yyyy-MM-dd");
				String realdate = date + " " + dateStr;
				rsDate = strToDateTime(realdate, "yyyy-MM-dd HH:mm:ss");
				return rsDate;
			} catch (Exception e) {
				rsDate = new Date();
				e.printStackTrace();
			}
		}
		if (dateStr.length() > 10) {
			try {
				rsDate = strToDateTime(dateStr, "yyyy-MM-dd HH:mm:ss");
				return rsDate;
			} catch (Exception e) {
				rsDate = new Date();
				e.printStackTrace();
			}
		} else {
			rsDate = new Date();
		}
		return rsDate;
	}

	public static boolean isDateBefore(String dateStr) {
		try {
			Date date = new Date();
			DateFormat df = DateFormat.getDateTimeInstance();
			return date.before(df.parse(dateStr));
		} catch (ParseException e) {
			return false;
		}
	}

	public static boolean isDateAfter(String dateStr) {
		try {
			Date date = new Date();
			DateFormat df = DateFormat.getDateTimeInstance();
			return date.after(df.parse(dateStr));
		} catch (ParseException e) {
			return false;
		}
	}

	/**
	 * 得到本月的第一天
	 * 
	 * @return
	 */
	@SuppressLint("SimpleDateFormat")
	public static String getMonthFirstDay(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.DAY_OF_MONTH,
				calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		return df.format(calendar.getTime());
	}

	/**
	 * 得到本月的最后一天
	 * 
	 * @return
	 */
	@SuppressLint("SimpleDateFormat")
	public static String getMonthLastDay(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.DAY_OF_MONTH,
				calendar.getActualMaximum(Calendar.DAY_OF_MONTH));

		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		return df.format(calendar.getTime());
	}

	@SuppressLint("SimpleDateFormat")
	public static String getNowDate() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateString = formatter.format(currentTime);
		return dateString;
	}
	
    public static String getWeekOfDate(Date dt) {
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return weekDays[w];
    }
}
